﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace QuickManager.Code
{
    public class VSBuild
    {
        public static void Execute(string devenvPath, string slnPath, BuildType buildType)
        {
            string buildMode = string.Empty,
                versionMode = string.Empty;
            switch (buildType)
            {
                case BuildType.Debug:
                    {
                        versionMode = "debug";
                        buildMode = "build";
                        break;
                    }
                case BuildType.Release:
                    {
                        versionMode = "release";
                        buildMode = "build";
                        break;
                    }
                case BuildType.ReDebug:
                    {
                        versionMode = "debug";
                        buildMode = "rebuild";
                        break;
                    }
                case BuildType.ReRelease:
                    {
                        versionMode = "release";
                        buildMode = "rebuild";
                        break;
                    }
            }
            if (Directory.Exists(Common.TemplateDir + "/bat/"))
            {
                Directory.Delete(Common.TemplateDir + "/bat/", true);
            }
            Directory.CreateDirectory(Common.TemplateDir + "/bat/");
            string devenvDir = Regex.Replace(devenvPath, "devenv\\.com$", "");
            string batName = Common.TemplateDir + "/bat/" + Guid.NewGuid() + ".bat";
            string logName = Regex.Replace(batName, ".bat$", ".log");

            List<string> commands = new List<string>();
            commands.Add(devenvPath.Split(':').First() + ":");  //进入盘符
            commands.Add("cd \"" + devenvDir + "\"");    //进入VS的devenv.com所在文件夹
            commands.Add(string.Format("devenv " + "\"" + slnPath + "\" /{0} {1} /out \"{2}\"", buildMode, versionMode, logName));  //编译项目
            commands.Add("pause");//cmd窗口保留

            File.WriteAllLines(batName, commands.ToArray(), Encoding.Default);
            try
            {
                Process process = new Process();
                process.StartInfo.FileName = batName;
                process.Start();
            }
            catch
            {
            }
        }
    }

    public enum BuildType
    {
        Debug,
        Release,
        ReDebug,
        ReRelease
    }
}
